﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;
using System.Reflection;

namespace Communicate
{
    public class AjaxServiceHandler : IHttpHandler, IRequiresSessionState
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext httpContext)
        {
            if (httpContext.Request.HttpMethod == "GET")
            {
                httpContext.Response.Write(new System.IO.StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Communicate.AjaxService.js")).ReadToEnd());
            }
            else
            {

                object result = null;
                try
                {
                    var form = httpContext.Request.Form;
                    if (form["Interfaces"] == "")
                    {
                        if (form["Method"] == "Login")
                        {
                            result = CommunicateManage.Login(form["Parameters0"], form["Parameters1"], httpContext.Session);
                        }
                        if (form["Method"] == "Logout")
                        {
                            httpContext.Session.Clear();
                        }
                    }
                    else
                    {
                        object context = CommunicateManage.GetContext(httpContext.Session);
                        if (context == null)
                            result = new CommunicateException(ExceptionType.Timeout, "Session为空，您还没有登录或者离开的时间太长！");
                        else
                        {
                            List<string> pars = new List<string>();
                            for (int i = 0; i < httpContext.Request.Form.Count - 2; i++)
                            {
                                pars.Add(form["Parameters" + i.ToString()]);
                            }
                            result = CommunicateManage.Invoke(form["Interfaces"], form["Method"], pars, context);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                        result = new CommunicateException(ExceptionType.External, ex.InnerException);
                    else
                        result = new CommunicateException(ExceptionType.Internal, ex);
                }
                httpContext.Response.Write(JsonSerializer.Serialize(result));
            }
        }
    }
}
